package com.galaxis.wms.security.utils;

import com.galaxis.wms.EnumConstant;
import com.galaxis.wms.entity.BasLoginAgent;
import com.galaxis.wms.entity.BasUser;
import com.yvan.core.DbConv;
import com.yvan.security.JwtTokenHolder;
import com.yvan.security.SecurityDataSource;
import com.yvan.security.model.SecurityContext;
import io.jsonwebtoken.Claims;

import static com.galaxis.wms.query.QBasLoginAgent.basLoginAgent;
import static com.galaxis.wms.query.QBasUser.basUser;

/**
 * 作者：lizw <br/>
 * 创建时间：2022/01/21 17:57 <br/>
 */
public class SecurityContextExtUtils {
    public static final String SYS_LOGIN_AGENT = "sys_login_agent";
    public static final String SYS_USER = "sys_user";
    public static final String BAS_STAFF = "bas_staff";
//    public static final String SYS_USER_OUTREVIEW = "sys_user_outreview";
//    public static final String SYS_USER_PICK = "sys_user_pick";
//    public static final String SYS_USER_OWNER = "sys_user_owner";
//    public static final String SYS_USER_OWNER_ID = "sys_user_owner_id";

    /**
     * 获取 login_id
     */
    public static Long getLoginId() {
        Claims claims = JwtTokenHolder.get();
        if (claims == null) {
            return null;
        }
        return claims.get(EnumConstant.JWT_EXT_LOGIN_ID, Long.class);
    }

    /**
     * 登录代理
     */
    public static BasLoginAgent fillLoginAgent(SecurityContext securityContext) {
        if (securityContext == null) {
            return null;
        }
        Long loginId = getLoginId();
        if (loginId == null) {
            return null;
        }
        return (BasLoginAgent) securityContext.getExt().computeIfAbsent(
                SYS_LOGIN_AGENT,
                key -> SecurityDataSource.getQueryDSL().select(basLoginAgent)
                        .from(basLoginAgent)
                        .where(basLoginAgent.loginId.eq(loginId))
                        .fetchOne()
        );
    }

    /**
     * 用户
     */
    public static BasUser fillUser(SecurityContext securityContext) {
        if (securityContext == null) {
            return null;
        }
        final Long userId = DbConv.asLong(securityContext.getUserInfo().getUserId());
        return (BasUser) securityContext.getExt().computeIfAbsent(
                SYS_USER,
                key -> SecurityDataSource.getQueryDSL().select(basUser)
                        .from(basUser)
                        .where(basUser.userId.eq(userId))
                        .fetchOne()
        );
    }
}
